

<template>
  <div class="app-container" v-loading="loading">
    <el-row class="_head">
      <el-col :span="8">
        打印机服务状态：{{printSocketOpen?'连接':'未连接'}}
      </el-col>
      <el-col :span="8">
        <el-select v-model="usbSelectPrinter" size="mini" placeholder="请选择打印机">
          <el-option v-for="(item,name) in usbPrinters" :key="name" :value="name" :label="name" >

          </el-option>
        </el-select>
        <el-button
            size="mini"
            type="info" plain
            @click="getPrinters"
        >扫描设备</el-button>

      </el-col>
      <el-col :span="8">
        打印机连接状态：{{onlineUsbBool ?'连接':'未连接' }}
        <el-button
            size="mini"
            type="info" plain
            @click="selectOnLineUsbPrinter"
        >连接打印机</el-button>
      </el-col>
    </el-row>

    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>用户信息</span>
      </div>
      <el-form ref="orderForm" :rules="rules" :model = "orderForm" label-width="120px" size="small" :inline="true" >
        <el-row>
          <el-col :span="8">
            <el-form-item label="用户ID" label-position="right" prop="userId">
              <el-input ref="userIdInput" v-model="orderForm.userId" placeholder="请输入用户ID" :disabled="scanSuccess"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="用户姓名" prop="userName">
              <el-input v-model="userInfo.userName" placeholder="请输入用户姓名" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-button type="primary" plain @click="queryUserInfo">查询用户信息</el-button>
            <el-button type="primary" plain @click="reset">重新扫码</el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="配送联系人" label-position="right" prop="userName">
              <el-input v-model="userInfo.userName" placeholder="请输入用户电话"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="配送电话" prop="phonenumber">
              <el-input v-model="userInfo.phonenumber" placeholder="请输入用户电话"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="配送地址" prop="address">
              <el-input v-model="userInfo.address" style="width: 800px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card class="box-card" style="margin-top: 20px">
      <div slot="header" class="clearfix">
        <span>订单信息</span>
      </div>

      <el-row>
        <el-form :model = "orderForm" size="small"  :inline="true" >
          <el-col :span="8">
            <el-form-item label="中药饮片数量(包)" prop="userId">
              <el-input  v-model="orderForm.medicineCount" placeholder="0" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总重量(g)" prop="userId">
              <el-input v-model="orderForm.weight" placeholder="请输入用户ID" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产出药剂数量(包)" prop="userId">
              <el-input  v-model="orderForm.resultCount" placeholder="请输入用户ID" ></el-input>
            </el-form-item>
          </el-col>
        </el-form>

      </el-row>
      <el-row>
        <el-table :data="orderDetail" style="width: 100%"  size="mini">
          <<el-table-column
            type="index"
            width="50">
        </el-table-column>
          <el-table-column label="煎药方式" align="center" width="300">
            <template slot-scope="scope">
              <el-select v-if="scope.row.isEdit" v-model="scope.row.optionType" placeholder="请选择煎药方式">
                <el-option
                    v-for="dict in dict.type.option_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
              <div v-else class="txt">{{scope.row.optionType}}</div>
            </template>
          </el-table-column>
          <el-table-column label="重量(g)" align="center" prop="weight" >
            <template slot-scope="scope">
              <el-input-number v-if="scope.row.isEdit" class="item" :min="0" v-model="scope.row.weight" :precision="2" placeholder="请输入内容"></el-input-number>
              <div v-else class="txt">{{scope.row.weight}}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row,scope.$index)"
                  v-hasPermi="['manage:detail:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="info" plain style="width: 100%" @click="addOrderDetail">新增</el-button>
      </el-row>
      <el-row :gutter="20" style="margin-top: 20px">
        <el-col :span="4" :offset="20">

          <el-button type="primary" @click="submitForm" :disabled="!canCommit">提  交</el-button>
          <el-button v-if="canPrint" type="primary" @click="printQR">打  印</el-button>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import {addOrder, getUserUserInfo} from "@/api/manage/order";
import {addDetails} from "@/api/manage/detail";
import Socket from "@/utils/Socket";
import NMPrintSocket from "@/utils/Print";
import Operlog from "@/views/monitor/operlog/index.vue";
import {qrCodePrintData} from "@/utils/printData/QrCode";
export default {
  components: {Operlog},
  name: "addOrder",
  dicts: ['option_type'],
  data() {
    return {
      printSocketOpen: false,
      usbSelectPrinter:"",
      usbPrinters: {},
      nMPrintSocket: null,
      onlineUsbBool:false,
      initSDKBool: false,
      selectedPrint:"",


      loading: false,
      deptId:null,
      orderForm: {
        userId: '',
        weight: 0.0,
        resultCount: 0,
        medicineCount: 0,
        status: 0
      },
      userInfo:{
        userName: '',
        address:'',
      },
      orderDetail:[],
      scanSuccess: false,
      canPrint: false,
      rules: {
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ]
      }
    }
  },

  watch:{
    orderDetail: {
      handler: function(newVal, oldVal) {
        let _totalWeight = 0;
        this.orderDetail.forEach(item => {
          _totalWeight += item.weight;
        })
        this.orderForm.weight = _totalWeight;
        this.orderForm.medicineCount = this.orderDetail.length;
      },
      deep: true,
      immediate: true
    }
  },
  created(){

    this.deptId = this.$store.getters.deptId
    this.$nextTick((_) => {
      this.$refs.userIdInput.focus();
    })
    this.initPrinter();
  },
  computed:{
    canCommit(){
      return this.scanSuccess && this.orderDetail.length!==0 && this.orderForm.resultCount!==0 && !this.canPrint;
    }
  },
  methods: {

    submitForm(){
      this.$refs["orderForm"].validate(valid => {
        if (valid) {
          this.loading = true;
          this.orderForm.deptId = this.deptId;
          console.log(this.orderForm);
          addOrder(this.orderForm).then((res) => {

            let _orderId = res.data.id
            this.orderDetail.forEach((item, index) => {
              item.orderId = _orderId;
            })
            console.log(this.orderDetail);
            addDetails(this.orderDetail).then(response => {
              this.$modal.msgSuccess("新增订单成功")
              this.canPrint = true;
            }).finally(()=>{
              this.loading = false;
            })
          }).catch(error => {
              this.loading = false;
          })
        }
      })
    },
    addOrderDetail(){
      this.orderDetail.push({ optionType:0,isEdit: true, weight:0})
    },
    handleDelete(row,index) {
      this.orderDetail.splice(index,1);
    },
    sleep(time) {
      return new Promise(resolve => setTimeout(resolve, time));
    },
    async printQR(){
      console.log("print");


      for(let i=0;i<this.orderDetail.length;i++){
        const qrCodeText = {type:"medicine",orderId:this.orderDetail[i].orderId ,index:(i+1)};
        this.print(qrCodeText, this.orderDetail.length);
        await this.sleep(5000);
      }




       // 休眠2秒
    },
    reset(){
      this.orderForm = {
        userId: '',
        weight: 0.0,
        resultCount: 0,
        medicineCount: 0,
        status: 0
      }
      this.userInfo = {
        userName: '',
      }
      this.$refs.userIdInput.focus();
      this.scanSuccess = false;
      this.orderDetail = [];

    },
    queryUserInfo() {
      this.loading = true;
      getUserUserInfo({userId: this.orderForm.userId})
          .then(response => {
            if(response.code == 200 && response.data.userId != undefined){
              this.userInfo = response.data;
              this.userInfo.address = "xxx街道10号"
              this.scanSuccess = true;
            } else {
              this.scanSuccess = false;
            }

      }).catch(()=>{
        this.scanSuccess = false;
      }).finally(()=>{
        this.loading = false;
      })
    },

    async initPrinter(){
      console.log("initPrinter");
      const socketData = new Socket("ws://127.0.0.1:37989");
      socketData.open(
          (openBool) => {
            console.log(openBool)
            this.printSocketOpen = openBool;
            console.log("开始调用获取打印机方法");
            this.getPrinters();
          },
          (msg) => {
            if (msg.resultAck.callback != undefined) {
              const callbackName = msg.resultAck.callback.name;
              const msgInfo = msg.resultAck.info;
              if (callbackName == "onCoverStatusChange") {
                //盒盖状态：0-闭合、1-打开
                console.log("盒盖状态", msgInfo.capStatus);
              } else if (callbackName == "onElectricityChange") {
                //"power" : 0-4, // 电池电量等级（共5档）
                console.log("电池电量等级", msgInfo.power);
              }

            }
          }
      );
      // 创建打印实例
      this.nMPrintSocket = new NMPrintSocket(socketData);
    },
    async getPrinters() {
      if (!this.printSocketOpen) {
        return this.$modal.msgWarning("打印服务未开启");
      }
      console.log("开始获取打印机");
      try {
        const allPrintersRes = await this.nMPrintSocket.getAllPrinters();
        if (allPrintersRes.resultAck.errorCode === 0) {
          const allPrinters = JSON.parse(allPrintersRes.resultAck.info);
          this.usbPrinters = { ...allPrinters };
          this.usbSelectPrinter = Object.keys(this.usbPrinters)[0];

          console.log(Object.keys(allPrinters)[0]);
          console.log(parseInt(this.usbPrinters[this.usbSelectPrinter]))


          this.selectOnLineUsbPrinter();
        } else {
          this.$modal.msgWarning("没有在线的打印机");
        }
      } catch (err) {
        console.error("getPrinters", err);
      }
    }
    ,
    // 连接打印机
    async selectOnLineUsbPrinter() {
      if (!this.printSocketOpen) {
        return this.$modal.msgWarning("打印服务未开启");
      }
      console.log("开始连接打印机");
      try {
        console.log(this.usbSelectPrinter)
        console.log(parseInt(this.usbPrinters[this.usbSelectPrinter]))
        const res = await this.nMPrintSocket.selectPrinter(
            this.usbSelectPrinter,
            parseInt(this.usbPrinters[this.usbSelectPrinter])
        );
        console.log(res.resultAck.errorCode);

        if (res.resultAck.errorCode === 0) {
          console.log("连接成功");
          this.onlineUsbBool = true;
          console.log("开始初始化SDK");
          this.initSDK();
        } else {

          console.log("连接失败");
          this.onlineUsbBool = false;
          this.$modal.msgWarning("连接失败");
        }
      } catch (err) {
        console.log("链接异常", err);
      }
    },
    //初始化SDK
    async initSDK() {
      if (!this.printSocketOpen) return this.$modal.msgWarning("打印服务未开启");

      try {
        const res = await this.nMPrintSocket.initSdk({ fontDir: "" });
        if (res.resultAck.errorCode == 0) {
          console.log("初始化成功");
          this.initSDKBool = true;
        } else {
          console.log("初始化失败");
          this.initSDKBool = false;
        }
      } catch (err) {
        console.error(err);
      }
    },

    async print(content,sum){
      console.log(content)
      // let c = {type : 'pan', id : item.id, name: item.panName}
      let jsonString = JSON.stringify(content);


      if(!this.printSocketOpen) return this.$modal.msgWarning("打印服务位开启");
      // 打印浓度、 纸张类型、 打印模式、 总打印份数
      // 纸张类型 1. 间隙纸
      const startRes = await this.nMPrintSocket.startJob(
          3,1, 1, 1
      );

      if (startRes.resultAck.errorCode == 0) {
        // 提交打印任务
        //设置画布尺寸
        console.log("画布：", qrCodePrintData.InitDrawingBoardParam);
        const res = await this.nMPrintSocket.InitDrawingBoard(
            {
              width: 30,
              height: 50,
              rotate: 90,
              path: "ZT001.ttf",
              verticalShift: 0,
              HorizontalShift: 0,
            }
        )
        if (res.resultAck.errorCode != 0) {
          console.log("设置画布失败")
          return;
        }

        // 绘制元素
        const r = await this.nMPrintSocket.DrawLableQrCode({
          x:3,
          y:15,
          height:25,
          width:25,
          value:jsonString,
          rotate:0,
          codeType:31
        });
        if(r.resultAck.result != 0) {
          console.log("绘制元素失败")
          return
        } else {
          console.log("绘制二维码成功")
        }
        console.log("===================")
        console.log( typeof(content) )
        console.log(content.orderId)
        let _msg = '订单:' + content.orderId + ' - ' + content.index +  '/' + sum;
        console.log(_msg)
        const r1 = await this.nMPrintSocket.DrawLableText({
          x:0,
          y:6,
          width: 30,
          rotate:0,
          fontSize: 3.0,
          textAlignHorizonral:1,
          path:"ZT001,ttf",
          value: _msg
        })
        if(r1.resultAck.result != 0) {
          console.log("绘制元素失败")
          return
        } else {
          console.log("绘制文字成功")
        }

        const jsonObj = {
          printerImageProcessingInfo:{
            printQuantity:2
          },
        };
        const commitRes = await this.nMPrintSocket.commitJob(
            null,
            JSON.stringify(jsonObj)
        );
        console.log(commitRes);
        if (
            commitRes.resultAck.printQuantity == jsonObj.printerImageProcessingInfo.printQuantity &&
            commitRes.resultAck.onPrintPageCompleted ==
            this.jsonObj.printerImageProcessingInfo.printQuantity
        ) {
          //结束打印任务
          const endRes = await this.nMPrintSocket.endJob();
          console.log(endRes);
          if (endRes.resultAck.errorCode === 0) {
            console.log("打印完成");
          }
          return;
        }

        if (commitRes.resultAck.errorCode === 0){
          // this.$modal.msgWarning("end")
        }


      }
    }
  },

}
</script>


<style scoped lang="scss">

</style>
